package com.document;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Random;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.apache.commons.io.FileUtils;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.converter.PicturesManager;
import org.apache.poi.hwpf.converter.WordToHtmlConverter;
import org.apache.poi.hwpf.usermodel.Picture;
import org.apache.poi.hwpf.usermodel.PictureType;
import org.apache.poi.hwpf.usermodel.Range;
import org.w3c.dom.Document;

import com.document.R;


import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.widget.TextView;
import android.widget.Toast;

//解析读取word工具类 
@SuppressLint("NewApi")
public class ViewFileword extends Activity {

	private WebView view;
	private TextView t;
	private String filepath;
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		 final Activity activity = this;
		getWindow().requestFeature(Window.FEATURE_PROGRESS);  		
        // 完成窗体的全屏显示  取消掉状态栏  
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, 
                WindowManager.LayoutParams.FLAG_FULLSCREEN); 
		setContentView(R.layout.view);		
		view = (WebView)findViewById(R.id.show);
		t=(TextView)findViewById(R.id.filename_1);
		view.setWebChromeClient(new WebChromeClient() {   
              
	            public void onProgressChanged(WebView view, int newProgress) {   
	                // 设置WebView加载进度条 
	                activity.setProgress(newProgress * 100);   
	            }   
	        });  
			
		 final String path = GetPath.getpath()+File.separator;
		 System.out.println(GetPath.getpath());
       
         Intent i=getIntent();
         Uri uri=(Uri)i.getData();
          filepath=uri.getPath(); 
         File f=new File(filepath);
         String fn=f.getName();
         t.setText(fn);
         //System.out.println(f);
         System.out.println(filepath);
         wordtohtml(filepath);
		 	//设置网页缩放
		view.getSettings().setSupportZoom(true);
		view.getSettings().setBuiltInZoomControls(true);
		view.getSettings().setDefaultTextEncodingName("UTF-8");
		view.getSettings().setUseWideViewPort(true);

		//view.getSettings().setLoadWithOverviewMode(true);
		view.loadUrl("file:/"+GetPath.getpath()+File.separator+"dhfj59rkek5orkt.html");
	}
	//重写onCreateContextMenu，实现复制文字
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		
		//实例化工具类
				WebViewCopy copy = new WebViewCopy(this, view);
			copy.onCreateContextMenu(menu, v, menuInfo,0,"复制"); 
			super.onCreateContextMenu(menu, v, menuInfo);
			}	
	@TargetApi(Build.VERSION_CODES.FROYO)
	@SuppressLint("NewApi")
	public void wordtohtml(String file){
		final String path = GetPath.getpath()+File.separator;
		try{
	 		System.out.println("ddd");
      InputStream input = new FileInputStream(file );
      
      HWPFDocument wordDocument = new HWPFDocument(input);
      WordToHtmlConverter wordToHtmlConverter = new WordToHtmlConverter(
    		  DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument());
      wordToHtmlConverter.setPicturesManager(new PicturesManager() {             
				@Override
				public String savePicture(byte[] content,
						PictureType pictureType, String suggestedName) {				
					return suggestedName;
				}
      });
   
      Range range=wordDocument.getRange();
      wordToHtmlConverter.processDocumentPart(wordDocument, range);    
      List pics = wordDocument.getPicturesTable().getAllPictures();
      if (pics != null) {
              for (int i = 0; i < pics.size(); i++) {
                      Picture pic = (Picture) pics.get(i);
                      try {
                              pic.writeImageContent(new FileOutputStream(path + pic.suggestFullFileName()));
                      } catch (FileNotFoundException e) {
                              e.printStackTrace();
                      }
              }
      }
    //解析word 转化为html文档
      Document htmlDocument = wordToHtmlConverter.getDocument();
      ByteArrayOutputStream outStream = new ByteArrayOutputStream();
      DOMSource domSource = new DOMSource(htmlDocument);
      StreamResult streamResult = new StreamResult(outStream);
      TransformerFactory tf = TransformerFactory.newInstance();
      Transformer serializer = tf.newTransformer();
      serializer.setOutputProperty(OutputKeys.ENCODING, "utf-8");
      serializer.setOutputProperty(OutputKeys.INDENT, "yes");
      serializer.setOutputProperty(OutputKeys.METHOD, "html");
      serializer.transform(domSource, streamResult);
      outStream.close();
      byte b_y[]=outStream.toByteArray();
      //设置边距
      b_y[147] = ' ';  
      String content = new String(b_y);
      System.out.println("content"+content);

      FileUtils.write(new File(path, "dhfj59rkek5orkt.html"), content, "utf-8");
      System.out.print("写入文件");
	 	}catch (Exception e) {
			// TODO: handle exception
		}
	}
	//添加菜单
	 public boolean onCreateOptionsMenu(Menu menu)    
	    {    
	            
	        menu.add(0, 0, 0, "截屏"); 
	        menu.add(0, 1, 0, "发送"); 
	        
	        
	        	          
	        return super.onCreateOptionsMenu(menu);    
	    }    
	    
	    @Override    
	    public boolean onOptionsItemSelected(MenuItem item)    
	    {    
	        switch(item.getItemId())    
	        {    
	            case 0:   
	                {   
	                	SimpleDateFormat formatter=new SimpleDateFormat("MM月dd日HH.mm.ss");       
	                	Date curDate=new Date(System.currentTimeMillis());//获取当前时间       
	                	String str=formatter.format(curDate);
	                	System.out.println(str);
	               	 ShotView.shot(this,"mnt/sdcard/DCIM/Word截图"+str+".png");
	                  
             Toast.makeText(getApplicationContext(), "截屏成功,已保存在mnt/sdcard/DCIM/Word截图"+str+".png", Toast.LENGTH_LONG).show();
             
	                    break;    
	                } 
	            case 1:   
                {   
                	//调用系统分享功能
		    		 Intent intent = new Intent(Intent.ACTION_SEND);  
		                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);  
		                intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(new File(filepath)));   
		                intent.setType("*/*");   //分享文件  
		                startActivity(Intent.createChooser(intent,"分享"));
		    		break;
         
                       
                } 
	                
	        }
			return false;}
		protected DecodeService createDecodeService() {
	
			return null;
		}

	}

